package cn.xiaolang.function.quartz;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import cn.xiaolang.common.utils.LoggerUtils;
import cn.xiaolang.common.utils.Monitor;

/**
 * 
 * 自定义job，执行相应的方法
 * @version 1.0
 * @since JDK1.7
 * @author fuhw
 * @date 2016年3月31日 下午4:35:28
 */
public class ZWJob implements Job{
	//任务job的id设置：实例类名+调度时间
	private final String JOB_ID = this.getClass().getName()+"_"+ DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
	
	protected String getJOB_ID() {
		return JOB_ID;
	}
	protected void before(){
		
	}
	protected void after(){
		
	}
	protected void doExecute(){
		
	}
	protected void doExecute(Map<String, Object> params){
		
	}

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		LoggerUtils.info(context.getJobDetail().getJobClass(), "================start=================");
		Monitor.begin();
		try {
			before();
			JobDataMap params = context.getJobDetail().getJobDataMap();
			if(params == null || params.isEmpty()){
				doExecute(null);
			}else{
				Map<String, Object> data = new HashMap<>();
				for(Entry<String, Object> entry:params.entrySet()){
					data.put(entry.getKey(), entry.getValue());
				}
				doExecute(data);
			}
		} catch (Exception e) {
			LoggerUtils.error(context.getJobDetail().getJobClass(), e, "任务执行异常");
		}finally{
			after();
		}
		LoggerUtils.info(context.getJobDetail().getJobClass(), "===============end by %f s==============",Monitor.end());
	}

}
